//
//  ZYEmoticonViewController.swift
//  01-表情键盘
//
//  Created by 陈宗毅 on 15/12/28.
//  Copyright © 2015年 czy. All rights reserved.
//

import UIKit

class ZYEmoticonViewController: UIViewController {

    // MARK: - 属性
    /// 表情要添加到的textView,控制器没有必要强引用
    weak var textView: UITextView?
    
    
    private let ReuseIdentifier = "ReuseIdentifier"
    
    ///表情包模型
    private let packages = ZYEmotionPackage.packages
    
    ///按钮起始tag
    var baseTag = 1000
    /// 选中按钮
    var selectedButton : UIButton?
    
    ///构造方法，需要传入textView
    init(textView:UITextView){
        self.textView = textView
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        prepareUI()
        
//        print(ZYEmotionPackage.loadPackage())
    }
    
    private func prepareUI()
    {
        view.addSubview(collectionView)
        view.addSubview(toolBar)
        //添加约束,表情键盘给其他工程使用,尽可能少的依赖第三方框架
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        toolBar.translatesAutoresizingMaskIntoConstraints = false
        
        //返回的是约束的数组
        // VFL
        // collectionView水平填充父控件
        // format: VFL语句 H: 表示水平 |父控件左边 | 父控件的右边 [] 有一个view [ view的左边 ]view的右边
        // 返回的是约束的数组
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[cv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["cv":collectionView]))
         // toolBar水平填充父控件
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[tb]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["tb":toolBar]))
        // 垂直方向
        // 1.collectionView的顶部和父控件的顶部重合
        // 2.collectionView的底部和toolBar的顶部重合
        // 3.toolBar高44
        // 4.toolBar底部和父控件的底部重合
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[cv]-0-[tb(44)]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["cv":collectionView,"tb":toolBar]))
        
        setupToolBar()
        
        setupCollectionView()
    }
    
   private func setupToolBar(){
        var items = [UIBarButtonItem]()
    
        var index = 0
        for package in packages!{
            
            let name = package.group_name_cn
            
            
            let button = UIButton()
            button.setTitle(name, forState: UIControlState.Normal)
            button.setTitleColor(UIColor.lightGrayColor(), forState: UIControlState.Normal)
            button.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Selected)
            button.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Highlighted)
            button.sizeToFit()
            
            button.addTarget(self, action: "buttonClick:", forControlEvents: UIControlEvents.TouchUpInside)
            button.tag = index + baseTag
            if index == 0 {
                SwitchSelecteButton(button)
            }
            
            let item = UIBarButtonItem(customView: button)
            
            items.append(item)
            
            items.append( UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
            
            index++
        }
        items.removeLast()
        toolBar.items = items
    }
    
    func buttonClick(button:UIButton)
    {
        print("点击了第\(button.tag - baseTag)组")
        //滚动到对应的表情包
        collectionView.scrollToItemAtIndexPath(NSIndexPath(forItem: 0, inSection: button.tag - baseTag), atScrollPosition: UICollectionViewScrollPosition.Left, animated: true)
        //选中点击的按钮
        SwitchSelecteButton(button)
    }
    /**
    选中某个按钮
    
    :param: button 要选中的按钮
    */
    private func SwitchSelecteButton(button:UIButton)
    {
        //三部曲
        
        selectedButton?.selected = false
        button.selected = true
        selectedButton = button
    }
    
    private func setupCollectionView(){
    
        //注册cell
        collectionView.registerClass(ZYEmotionCell.self, forCellWithReuseIdentifier: ReuseIdentifier)
        //设置数据源
        collectionView.dataSource = self
        collectionView.delegate = self
    
    }
    

    //MARK: - 懒加载
    ///collectionView:直接创建布局赋值
    private lazy var collectionView:UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: ZYCollectionViewFlowLayout())
    /// toolBar
    private lazy var toolBar:UIToolbar = UIToolbar()
    
    

}
// 继承系统的流水布局 UICollectionViewFlowLayout, 来覆盖prepareLayout来设置layout的参数
class ZYCollectionViewFlowLayout: UICollectionViewFlowLayout {
    // 覆盖父类的方法
    override func prepareLayout() {
        super.prepareLayout()
        
        let itemWidth = collectionView!.frame.width / 7
        let itemHeight = collectionView!.frame.height / 3
        self.itemSize = CGSize(width: itemWidth, height: itemHeight)
        //取消间距
        minimumInteritemSpacing = 0
        minimumLineSpacing = 0
        //滚动方向
        scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        collectionView?.pagingEnabled = true
        collectionView?.bounces = false
        collectionView?.showsHorizontalScrollIndicator = false
    }
}
// MARK: - 扩展 CZEmoticonViewController 实现 UICollectionViewDataSource
extension ZYEmoticonViewController:UICollectionViewDataSource,UICollectionViewDelegate
{
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        
        return packages?.count ?? 0
    }
    
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    
        let package = packages![section]
        return package.emoticons.count
    
    }
    
    
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ReuseIdentifier, forIndexPath: indexPath) as! ZYEmotionCell
        
//        cell.backgroundColor = UIColor.randomColor()
        
        let package = packages![indexPath.section]
        cell.emotion = package.emoticons[indexPath.item]
        
        return cell
    }
    
//    监听collectionView停止滚动
    func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        let showIndexPaths = collectionView.indexPathsForVisibleItems()
        
        let indexPath = collectionView.indexPathsForVisibleItems()[10]
        
        let showSection = indexPath.section
        
        let button = toolBar.viewWithTag(showSection + baseTag) as! UIButton
        SwitchSelecteButton(button)
    }
    // 监听collectionViewcell的点击事件, cell的点击事件会被按钮的抢走(被按钮消费了)
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        //获取对应的表情包
        let pakage = packages![indexPath.section]
        //获取对应的模型
        let emoticon = pakage.emoticons[indexPath.item]
//        print("点击的模型：\(emoticon)")
        textView?.insertEmoticon(emoticon)
        
        // 在最近表情里面点击同一个表情时,会发现添加在textView上的表情不是点击的表情,原因是因为表情模型重新排序,但是显示没有更新
        // 方法1,更新collectionView的第0组
        //        collectionView.reloadSections(NSIndexSet(index: 0))
        // 方法2.点击最近里面的表情不参与排序,不需要在添加到最近表情包
        if indexPath.section != 0 {
            ZYEmotionPackage.addFavorateEmoticon(emoticon)
        }
        

    }
 }


